


class ItemOutput:

    def __init__(self,imagepath=None,text=None):
        self.imagepath = imagepath
        self.text = text

    def open_to_json(self):
        if self.imagepath:
            return {
                "image": open(self.imagepath,"r"),
                "text": self.text
            }
        else:
            return { "text": self.text }
 


class GroupItem:

    IMAGETAG = "<ImageHere>"

    def __init__(self,image=None,**kwargs):
        self.kwargs = kwargs
        self.imagepath = None
        if image:
            self.imagepath = image
            self.kwargs["image"] = self.IMAGETAG
        self.keys = list(kwargs.keys())
    
    def get_image_path(self):
        return self.imagepath
    
    def __extract_kwargs(self,template:str):
        kwargs = {}
        for key in self.keys:
            item = "{" + str(key) + "}"
            if item in template:
                kwargs[key] = self.kwargs[key]
        return kwargs
    
    def __make(self,template:str,allmatch=True):
        kwargs = self.__extract_kwargs(template)
        if allmatch:
            return template.format_map(kwargs)
        else:
            result = str(template)
            for key,value in kwargs.items():
                item = "{" + str(key) + "}"
                result = result.replace(item,str(value))
            return result

    def Make(self,template:str,allmatch=True):
        return self.__make(template,allmatch)
    
    def OutJson(self,template:str,allmatch=True):
        text = self.__make(template,allmatch)
        return ItemOutput(self.imagepath,text)
    


template = "{image}, {name} is {age}"

item = GroupItem(name='sdf',age='1234',image="main.py")
a = item.Make(template)
print(a)

a = item.OutJson(template)
print(a.open_to_json())





